using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Vin.Extension.Framework.AntChain.Adapter;
using Vin.Extension.Framework.AntChain.Dto;
using Vin.Tool.Core.AssemblyCategory;
using Vin.Tool.Core.BasicTypeCategory;
using Vin.Tool.Core.JsonCategory;
using Vin.Tool.Core.NetCategory;

namespace Vin.Extension.Framework.AntChain;

public static class AntChainEndpoint
{
    private static List<IAntChainNotify> Callbacks => AssemblyTool.GetTypes<IAntChainNotify>()
        .Select(Activator.CreateInstance)
        .Cast<IAntChainNotify>()
        .ToList();

    public static void UseAntChainNotify(WebApplication app, string notifyUrl)
    {
        app.MapGet(notifyUrl, async (HttpRequest request) =>
        {
            var context = request.HttpContext;
            var dto = context.QueryToObject<AntChainNotifyModel>(JsonTool.JsonOptionsType.UnderLineLower);

            foreach (var antChainNotify in Callbacks.Where(x => x.MsgType == dto.MsgType).OrderBy(m => m.Order))
            {
                await antChainNotify.NotifyAsync(context, dto);
            }

            return TypedResults.Content("success");
        });
    }
}